<?php


namespace App\Services;

use App\Models\StoreInfo;
use App\Models\UserStoreLogs;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class StoreService
{
    private const URL = 'https://restapi.amap.com/v3/geocode/geo?parameters';

    private $storeInfo;

    public function __construct()
    {
        $this->storeInfo = new StoreInfo();
    }

    public function getLocation(string $address, string $city = '')
    {
        $data = [
            'key'   => '4abef841d629ff03f514f9d47eeb7051',
            'address' => $address,
            'city'    => $city,
        ];
        $response = Http::get(self::URL, $data);
        if (empty($response->json()) || empty($response->json()['geocodes']) || empty($response->json()['geocodes'][0])) {
            return [];
        }

        $geoData = $response->json()['geocodes'];
        $data = $geoData[0]['location'];
        if (empty($data)) {
            return [];
        }
        $data = explode(',', $data);

        return [
            'lng'   => $data[0],
            'lat'   => $data[1],
            'district' => !empty($geoData[0]['district']) ? $geoData[0]['district'] : '',
        ];
    }

    public function getDealers()
    {
        $data = DB::table('users')->where('user_type', '3')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id')
            ->whereNotNull('users.address')
            ->where('user_type', 3)
            ->select('users.id', 'users.address', 'cities.simplified_chiness_value as city_name', 'province_master.simplified_chiness_value as province_name')
            ->limit(3000)
            ->get();
        if (empty($data)) {
            return [];
        }

        foreach ($data as $item) {
            if (empty($item->city_name) || empty($item->address)) {
                continue;
            }
            if (mb_strpos($item->address, '市') !== false) {
                $location = $this->getLocation($item->address, '');
            } else {
                $location = $this->getLocation($item->address, $item->city_name);
            }
            if (empty($location)) {
                continue;
            }

            DB::table('users')
                ->where('id', $item->id)
                ->update([
                'lng' => $location['lng'],
                'lat' => $location['lat'],
                'district' => $location['district'],
            ]);
        }
    }

    public function list()
    {

    }

    public function getStoreInfo(int $id)
    {
        $data = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id')
            ->where('users.id', $id)
            ->select( 'store_info.*', 'users.mdtype', 'store_info.persons', 'store_info.id as store_id', 'users.unique_id', 'users.company_name', 'users.id', 'users.abbr', 'users.status', 'users.first_name', 'users.cell_phone', 'users.phone_number', 'users.address', 'cities.simplified_chiness_value as city_name', 'province_master.simplified_chiness_value as province_name')
            ->first();

        return $data;
    }

    public function getStoreLocation(int $userId)
    {
        $user = DB::table('users')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id')
            ->whereNotNull('users.address')
            ->where('users.id', $userId)
            ->select('users.id', 'users.address', 'cities.simplified_chiness_value as city_name', 'province_master.simplified_chiness_value as province_name')
            ->first();

        if (empty($user)) {
            throw new \Exception('经销商数据不存在', 10000);
        }

        $location = $this->getLocation($user->city_name, $user->address);
        DB::table('users')
            ->where('id', $user->id)
            ->update([
                'lng' => $location['lng'],
                'lat' => $location['lat'],
            ]);
    }

    public function save(array $input)
    {
        $user = DB::table('store_info')->where('user_id', $input['xgmsid'])->first();
        if (!empty($user) && $user->is_delete != 1) {
            throw new \Exception('已添加成功不可重复添加');
        }

        if (!empty($user) && $user->is_delete == 1) {
            return $this->update($input['xgmsid'], $input);
        }

        $this->getStoreLocation($input['xgmsid']);
        $this->storeInfo->user_id = $input['xgmsid'];
        $this->storeInfo->store_level = $input['store_level'];
        $this->storeInfo->start_date = $input['startdate'];
        $this->storeInfo->end_date = $input['enddate'];
        $this->storeInfo->open_time = $input['start_time'];
        $this->storeInfo->close_time = $input['end_time'];
        $this->storeInfo->video_url = $input['video_url'];
        $this->storeInfo->is_advanced = $input['is_advanced'];
        $this->storeInfo->front_show = $input['front_show'];
        $this->storeInfo->detail = $input['content'];
        if (!empty($input['storage_images'])) {
            $this->storeInfo->honor_images = implode(',', $input['storage_images']);
        }
        if (!empty($input['qrcode_images'])) {
            $this->storeInfo->qrcode_url = implode(',', $input['qrcode_images']);
        }
        if (!empty($input['images'])) {
            $this->storeInfo->picture_url = implode(',', $input['images']);
        }
        $this->storeInfo->save();
        $id = $this->storeInfo->id;
        if (empty($id)) {
            throw new \Exception('添加失败');
        }

        if (empty($input['features_images']) || empty($input['detail_desc'])) {
            throw new \Exception('缺少特色信息');
        }
        $insertData = [];
        foreach ($input['features_images'] as $key => $features_image) {
            $insertData[] = [
                'store_id'  => $id,
                'picture_url'   => $features_image,
                'detail'        => $input['detail_desc'] && !empty($input['detail_desc'][$key]) ? $input['detail_desc'][$key] : '',
            ];
        }
        if (!empty($insertData)) {
            DB::table('store_features')->insert($insertData);
        }
    }

    public function update(int $id, array $input)
    {
        $this->getStoreLocation($id);

        $store = DB::table('store_info')->where('user_id', $id)->first();

        $updateData['start_date'] = $input['startdate'];
        $updateData['end_date'] = $input['enddate'];
        $updateData['open_time'] = $input['start_time'];
        $updateData['close_time'] = $input['end_time'];
        $updateData['video_url'] = $input['video_url'];
        $updateData['is_advanced'] = $input['is_advanced'];
        $updateData['front_show'] = $input['front_show'];
        $updateData['store_code'] = $input['store_code'];
        $updateData['detail'] = $input['content'];
        $updateData['persons'] = $input['persons'];
        $updateData['user_id'] = $id;
        if (!empty($input['storage_images'])) {
            $updateData['honor_images'] = implode(',', $input['storage_images']);
        }
        if (!empty($input['images'])) {
            $updateData['picture_url'] = implode(',', $input['images']);
        }
        if (!empty($input['qrcode_images'])) {
            $updateData['qrcode_url'] = implode(',', $input['qrcode_images']);
        }
        $updateData['is_delete'] = 0;
        if (empty($store)) {
            $store_id = DB::table('store_info')->insertGetId($updateData);
        } else {
            DB::table('store_info')->where('user_id', $id)->update($updateData);
            $store_id = $store->id;
        }
        if (empty($input['features_images']) || empty($input['detail_desc'])) {
            throw new \Exception('缺少特色信息');
        }
        if (empty($input['picture_images']) || empty($input['picture_desc'])) {
            throw new \Exception('缺少展示图片');
        }

        DB::table('store_features')->where('store_id', $store_id)->delete();
        $insertData = [];
        foreach ($input['features_images'] as $key => $features_image) {
            $insertData[] = [
                'store_id'  => $store_id,
                'picture_url'   => $features_image,
                'detail'        => $input['detail_desc'] && !empty($input['detail_desc'][$key]) ? $input['detail_desc'][$key] : '',
                'type'          => 1,
            ];
        }
        if (!empty($insertData)) {
            DB::table('store_features')->insert($insertData);
        }
        $insertData = [];
        foreach ($input['picture_images'] as $key => $features_image) {
            $insertData[] = [
                'store_id'  => $store_id,
                'picture_url'   => $features_image,
                'detail'        => $input['picture_desc'] && !empty($input['picture_desc'][$key]) ? $input['picture_desc'][$key] : '',
                'type'          => 2,
            ];
        }
        if (!empty($insertData)) {
            DB::table('store_features')->insert($insertData);
        }
    }

    //获取门店变动记录数量
    public function getStoreChangeCount(int $type): int
    {
        return DB::table('user_store_logs')
            ->selectRaw("distinct(user_id)")
            ->where('type', $type)
            ->where("date", date("Y-m", time()))
            ->count();
    }

    public function getStoreChangeList(): array
    {
        return [
            UserStoreLogs::TYPE_NEW => $this->getStoreChangeCount(UserStoreLogs::TYPE_NEW ),
            UserStoreLogs::TYPE_UP => $this->getStoreChangeCount(UserStoreLogs::TYPE_UP ),
            UserStoreLogs::TYPE_DOWN => $this->getStoreChangeCount(UserStoreLogs::TYPE_DOWN ),
            UserStoreLogs::TYPE_STOP => $this->getStoreChangeCount(UserStoreLogs::TYPE_STOP )
        ];
    }

    public function addStoreChangeLog($type,$userId) {
        $insertData = [
            "date" => date("Y-m",time()),
            "user_id" => $userId,
            "type" => $type,
        ];
        DB::table('user_store_logs')->insert($insertData);
    }
}